﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using Yitter.IdGenerator;

namespace BW.MesProject.BasicData.Application
{
    /// <summary>
    /// 产品物料服务实现类
    /// </summary>
    public class ProductItemServices : IProductItemServices
    {
        private readonly IBaseRepository<ProductItemModel> product;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="product">产品物料仓储</param>
        /// <param name="mapper">AutoMapper映射器</param>
        public ProductItemServices(IBaseRepository<ProductItemModel> product, IMapper mapper)
        {
            this.product = product;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加或更新产品物料信息
        /// </summary>
        /// <param name="model">产品物料模型</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> AddProductItem(ProductItemModel model)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                int rows = 0;
                if (model.Id > 0)
                {
                    // 修改
                    // 获取原始数据
                    var existingModel = product.GetValue(x => x.Id == model.Id && !x.IsDeleted);
                    if (existingModel == null)
                    {
                        result.Code = ApiEnums.Fail;
                        result.Message = "产品物料不存在";
                        result.Data = 0;
                        return result;
                    }

                    // 手动更新属性
                    existingModel.Productitemcode = model.Productitemcode;
                    existingModel.Productitemname = model.Productitemname;
                    existingModel.Productitemspecification = model.Productitemspecification;
                    existingModel.Productitemunit = model.Productitemunit;
                    existingModel.Productitemwarningvalue = model.Productitemwarningvalue;
                    existingModel.Processrouteid = model.Processrouteid;
                    existingModel.Materialgroupid = model.Materialgroupid;
                    existingModel.Producttype = model.Producttype;
                    existingModel.Productitemdescribe = model.Productitemdescribe;
                    existingModel.Productattributes = model.Productattributes;
                    existingModel.UpdatedTime = DateTime.Now;
                    existingModel.UpdatedBy = "admin";

                    rows = product.Update(existingModel);
                }
                else
                {
                    // 添加
                    // 使用雪花算法生成ID
                    model.Id = YitIdHelper.NextId();

                    // 如果没有提供编码，生成一个新的编码
                    if (string.IsNullOrEmpty(model.Productitemcode))
                    {
                        model.Productitemcode = $"PI{DateTime.Now.ToString("yyyyMMddHHmmss")}{new Random().Next(100, 999)}";
                    }

                    model.CreatedTime = DateTime.Now;
                    model.CreatedBy = "admin";
                    model.UpdatedTime = DateTime.Now;
                    model.UpdatedBy = "admin";
                    model.IsDeleted = false;

                    rows = product.Add(model);
                }

                if (rows > 0)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = model.Id > 0 ? "产品物料更新成功" : "产品物料添加成功";
                    result.Data = rows;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "操作失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = 0;
            }
            return result;
        }

        /// <summary>
        /// 删除产品物料（逻辑删除）
        /// </summary>
        /// <param name="id">产品物料ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> DeleteProductItem(long id)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var model = product.GetValue(x => x.Id == id && !x.IsDeleted);
                if (model == null)
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "产品物料不存在";
                    result.Data = 0;
                    return result;
                }

                // 逻辑删除：修改IsDeleted状态
                model.IsDeleted = true;
                model.UpdatedBy = "admin";
                model.UpdatedTime = DateTime.Now;

                var rows = product.Update(model);

                if (rows > 0)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = "产品物料删除成功";
                    result.Data = rows;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "产品物料删除失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = 0;
            }
            return result;
        }

        /// <summary>
        /// 获取所有产品物料
        /// </summary>
        /// <returns>产品物料列表</returns>
        public ApiResult<List<ProductItemModel>> GetAllProductItem()
        {
            ApiResult<List<ProductItemModel>> result = new ApiResult<List<ProductItemModel>>();
            try
            {
                var list = product.GetAll().Where(x => !x.IsDeleted).ToList();

                result.Code = ApiEnums.Success;
                result.Message = "获取产品物料列表成功";
                result.Data = list;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = new List<ProductItemModel>();
            }
            return result;
        }

        /// <summary>
        /// 分页查询产品物料
        /// </summary>
        /// <param name="Productitemcode">产品物料编码</param>
        /// <param name="Productitemname">产品物料名称</param>
        /// <param name="Producttype">产品类型</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">每页大小</param>
        /// <returns>分页结果</returns>
        public ApiPaging<ProductItemModel> GetProductItem(string? Productitemcode, string? Productitemname, string? Producttype, int pageindex, int pagesize)
        {
            ApiPaging<ProductItemModel> result = new ApiPaging<ProductItemModel>();
            try
            {
                var query = product.GetAll().Where(x => !x.IsDeleted);

                // 构建查询条件
                if (!string.IsNullOrEmpty(Productitemcode))
                {
                    query = query.Where(p => p.Productitemcode.Contains(Productitemcode));
                }

                if (!string.IsNullOrEmpty(Productitemname))
                {
                    query = query.Where(p => p.Productitemname.Contains(Productitemname));
                }

                if (!string.IsNullOrEmpty(Producttype) && float.TryParse(Producttype, out float typeValue))
                {
                    query = query.Where(p => p.Producttype == typeValue);
                }

                // 计算总条数
                int totalCount = query.Count();

                // 分页获取数据
                var pageData = query.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();

                result.Code = ApiEnums.Success;
                result.Message = "获取产品物料分页数据成功";
                result.Data = null; // ApiPaging需要一个Data属性
                result.PageData = pageData;
                result.TotalCount = totalCount;
                result.PageNum = pageindex;
                result.PageSize = pagesize;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = null;
                result.PageData = new List<ProductItemModel>();
                result.TotalCount = 0;
            }
            return result;
        }

        /// <summary>
        /// 根据ID获取产品物料
        /// </summary>
        /// <param name="id">产品物料ID</param>
        /// <returns>产品物料信息</returns>
        public ApiResult<ProductItemModel> GetProductItemById(long id)
        {
            ApiResult<ProductItemModel> result = new ApiResult<ProductItemModel>();
            try
            {
                var model = product.GetValue(x => x.Id == id && !x.IsDeleted);

                if (model != null)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = "获取产品物料信息成功";
                    result.Data = model;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "未找到指定ID的产品物料";
                    result.Data = null;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = null;
            }
            return result;
        }
    }
}
